package com.sw.haruka.module.share.server;

import com.sw.haruka.helper.utils.LogMgr;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by Swsbty on 2021/05/28
 */
public class ServerManager {

    private static ServerManager instance;

    private List<ServerObserver> observers;
    private ScheduledThreadPoolExecutor threadPool;
    private ExecutorService notifyThreadPool = Executors.newCachedThreadPool();
    private Server server;
    private final int INTERVAL_TIME = 1;

    private ServerManager() {
        server = new Server(this);
        observers = new CopyOnWriteArrayList<>();
        threadPool = new ScheduledThreadPoolExecutor(1);
        Runnable runnable = () -> {
            notifyStatus();
        };
        threadPool.scheduleAtFixedRate(runnable, 0, INTERVAL_TIME, TimeUnit.SECONDS);
    }

    public static ServerManager getInstance() {
        if (instance == null) {
            instance = new ServerManager();
        }
        return instance;
    }
    public void addObserver(ServerObserver observer) {
        observers.add(observer);
    }
    public void removeObserver(ServerObserver observer) {
        observers.remove(observer);
    }

    public void notifyStatus() {
        for (ServerObserver observer : observers) {
            List<Task> tasks = server.getCurrentTasks();
            LogMgr.INSTANCE.d("server current size of task: " + tasks.size());
            observer.currentTaskList(tasks);
        }
    }

    public void notifyNewTask(Task task) {
        notifyThreadPool.execute(() -> {
            for (ServerObserver observer : observers) {
                observer.newTask(task);
            }
        });
    }

    public void addTask(Task task) {
        server.addTask(task);
    }

}
